﻿using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace DapperRepository.DbContext
{
    public class RepositoryContext: DisposableObject,IRepositoryContext
    {
        //private readonly ConnectionStringSettings _connectionSeting =
        //    ConfigurationManager.ConnectionStrings["BudisengFirstDemoInfo"];

        private readonly string _connectionString;
        public RepositoryContext() { }

        public RepositoryContext(ConnectionStrings connectionStrings)
        {
            // TODO: Complete member initialization
            this._connectionString = connectionStrings.TestConnectionString;
            InitConnection();
        }

        public RepositoryContext(string connectionString)
        {
            this._connectionString = connectionString;
        }

        public IDbConnection GetDbConnection()
        {
            //if (Conn != null) return Conn;
            this.Conn = this.Conn ?? (this.Conn = new SqlConnection
            {
                ConnectionString = _connectionString
            });
            return Conn;
        }

        private IDbConnection Conn { set; get; }

        private void InitConnection()
        {
            this.Conn = this.Conn ?? (this.Conn = new SqlConnection
            {
                ConnectionString = _connectionString
            });            
            //DbProviderFactory dbfactory = DbProviderFactories.GetFactory(this._connectionSeting.ProviderName);
            //this.Conn = dbfactory.CreateConnection();
            //if (Conn != null) this.Conn.ConnectionString = this._connectionSeting.ConnectionString;
        }
        protected override void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }
            if (this.Conn.State != ConnectionState.Open) return;            
            this.Conn.Close();
            this.Conn.Dispose();
        }
    }
}
